package com.baizan.daka.ui.fragment

import android.os.Bundle
import com.baizan.daka.base.BasePageListFragment
import com.baizan.daka.event.ReceiveTastEvent
import com.baizan.daka.event.TastMrgEvent
import com.baizan.daka.mvp.model.bean.TaskInfoBean
import com.baizan.daka.net.BasePageResponse
import com.baizan.daka.ui.activity.PublishTaskActivity
import com.baizan.daka.ui.adapter.TaskMgrAdapter
import com.baizan.daka.ui.contract.TaskMgrContract
import com.baizan.daka.ui.presenter.TaskMgrPresenter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class TaskMgrFragment : BasePageListFragment<TaskMgrPresenter, TaskMgrAdapter>(),
    TaskMgrContract.View {
    var usedFlag: Int? = null

    companion object {
        fun newInstance(usedFlag: Int?): TaskMgrFragment {
            val fragment = TaskMgrFragment()
            usedFlag?.let {
                val bundle = Bundle()
                bundle.putInt("key", usedFlag)
                fragment.arguments = bundle
            }
            return fragment
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun upOrDownEvent(event: TastMrgEvent) {
        adapter?.let {
            val mData = it.data
            for ((index, bean) in mData.withIndex()) {
                if (bean.id == event.id.toLong()) {
                    it.notifyItemRemoved(index)
                }
            }
        }
    }
    override fun initData() {
        super.initData()
        usedFlag = arguments?.getInt("key")
        adapter?.setOnItemClickListener {
                adapter, view, position ->
          var item = adapter.data.get(position)
            item as TaskInfoBean
            context?.let {
                PublishTaskActivity.start(it,item)
            }

        }
    }

    override fun onRefresh() {
        presenter?.loadList(mCurrentPageNo, usedFlag)
    }

    override fun onLoadMore() {
        presenter?.loadList(mCurrentPageNo, usedFlag)
    }

    override fun initAdapter(): TaskMgrAdapter = TaskMgrAdapter()

    override fun initPresenter(): TaskMgrPresenter = TaskMgrPresenter(this)

    override fun initView() {

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun start() {
        EventBus.getDefault().register(this)
        presenter?.loadList(mCurrentPageNo, usedFlag)
    }


    override fun loadListSuccess(data: BasePageResponse<TaskInfoBean>) {
        getDatasSuccess(data)
    }

}